package com.seed.application;

import com.mybatisflex.core.FlexGlobalConfig;
import com.seed.core.dialect.impl.DialectDDLImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

@Component
public class SaInitializer implements CommandLineRunner {

    private final ApplicationContext applicationContext;

    public SaInitializer(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        Sa.setApplicationContext(applicationContext);
        Sa.setDataSourceKeyContext();
        String type = getDatabaseType();
        Sa.setDdl(new DialectDDLImpl(type));
        Sa.setSeedContext();
    }

    public String getDatabaseType() {
        DataSource dataSource = FlexGlobalConfig.getDefaultConfig().getDataSource();
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData dbMetaData = connection.getMetaData();
            return dbMetaData.getDatabaseProductName();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
